import { onMounted, onUnmounted } from "vue"
function removeDefaultEvent(event) {
	event.preventDefault()
	event.stopPropagation()
}
export default function useDrop(draggerDom, httpRequest, couldUpload, success, auto = true) {
	async function onDrop(event) {
		removeDefaultEvent(event)
		if (!couldUpload.value) {
			return
		}
		draggerDom.value.classList.remove("on-drager")
		if (!event.dataTransfer?.files.length) {
			return
		}
		success(await httpRequest(event.dataTransfer.files))
	}
	function onDragover(event) {
		removeDefaultEvent(event)
		if (!couldUpload.value) {
			return
		}
		draggerDom.value.classList.add("on-drager")
	}
	function onDragleave(event) {
		removeDefaultEvent(event)
		draggerDom.value.classList.remove("on-drager")
	}
	if (auto) {
		onMounted(createHandler)
		onUnmounted(unMountedHandler)
	}
	function createHandler() {
		unMountedHandler()
		draggerDom.value && draggerDom.value.addEventListener("dragover", onDragover)
		draggerDom.value && draggerDom.value.addEventListener("dragleave", onDragleave)
		draggerDom.value && draggerDom.value.addEventListener("drop", onDrop)
	}
	function unMountedHandler() {
		draggerDom.value && draggerDom.value.removeEventListener("dragover", onDragover)
		draggerDom.value && draggerDom.value.removeEventListener("dragleave", onDragleave)
		draggerDom.value && draggerDom.value.removeEventListener("drop", onDrop)
	}
	return {
		createHandler,
		unMountedHandler,
	}
}
